package com.hsyt.pfc.support.util;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: hs-med 上下文(线程安全) 存去全文需要的信息
 * @ClassName: MedContext
 * @Project: idea_project
 * @Package: com.hsyt.pfc.support.util
 * @Author: wangze@hsyuntai.com
 * @Date: 2015 年 09 月 02 日 11:21
 * @Copyright: 版权归 Hundsun 所有 <ModifyLog>
 * @ModifyContent:
 * @Author:
 * @Date: </ModifyLog>
 */
public class MedContext {

    private ThreadLocal<Map<MedKey, String>> contextMap;

    private static MedContext INSTANCE = new MedContext();

    public static final MedContext newInstance() {
        return INSTANCE;
    }

    private MedContext() {
        contextMap = new ThreadLocal<>();
    }

    /**
     * 线程安全存储到contextMap中
     *
     * @param key
     */
    public void setValue(MedKey key, Object val) {
        Map<MedKey, String> map = contextMap.get();
        if (map == null) {
            map = new HashMap<>();
        }
        if (null != val) {
            String valStr = null;
            if (String.class.isAssignableFrom(val.getClass())) {
                valStr = (String) val;
            } else {
                valStr = JSON.toJSONString(val);
            }
            map.put(key, valStr);
        }
        contextMap.set(map);
    }

    /**
     * 线程安全获取contextMap中的key对应的值
     *
     * @param key
     * @return
     */
    public String getValue(MedKey key) {
        Map<MedKey, String> map = contextMap.get();
        if (null == map) {
            return null;
        }
        return map.get(key);
    }

    public <T> T getValue(MedKey key, Class<T> clazz) {
        Map<MedKey, String> map = contextMap.get();
        if (null == map) {
            return null;
        }
        String valStr = map.get(key);
        if (StringUtil.isEmpty(valStr)) {
            return null;
        }
        return JSON.parseObject(valStr, clazz);
    }

    public void clearValue(MedKey key) {
        Map<MedKey, String> map = contextMap.get();
        if (null != map) {
            String valStr = map.get(key);
            if (StringUtil.isNotEmpty(valStr)) {
                map.put(key, null);
            }
        }

    }

    public enum MedKey {
        USER_INFO, UDB_TOKEN_INFO;

        public static MedKey getKey(String key) {
            for (MedKey medKey : MedKey.values()) {
                if (medKey.toString().equals(key)) {
                    return medKey;
                }
            }
            return null;
        }
    }

}
